#!/bin/sh

# Copyright 2014 Timothy Edward Baldwin

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


make_node() {
  # Create network napespace
  ip netns add navalis-test-$2
  ip netns exec navalis-test-$2 sysctl -w net.ipv4.conf.all.rp_filter=0
  ip netns exec navalis-test-$2 sysctl -w net.ipv4.conf.default.rp_filter=0
  ip netns exec navalis-test-$2 ip link set lo up

  # Enable routing
  if test "$1" != "host"; then
    ip netns exec navalis-test-$2 sysctl -w net.ipv4.conf.all.forwarding=1
  fi

  # Attach to parent
  if test "x$3" != "x"; then
    ip link add veth-$3 type veth peer name veth-$2
    ip link set veth-$3 netns navalis-test-$2
    ip link set veth-$2 netns navalis-test-$3
    ip netns exec navalis-test-$3 ip link set veth-$2 up
    ip netns exec navalis-test-$2 ip link set veth-$3 up
    ip netns exec navalis-test-$3 ip addr add dev veth-$2 192.168.$2.$3/24
    ip netns exec navalis-test-$2 ip addr add dev veth-$3 192.168.$2.$2/24
    ip netns exec navalis-test-$2 ip route add default via 192.168.$2.$3
  fi

  # Enable NAT
  if test "$1" = "nat"; then
    ip netns exec navalis-test-$2 iptables -t nat -A POSTROUTING -o veth-$3 -j MASQUERADE --random
  fi
}

# Remove old
for i in $(seq 1 10); do
  ip netns delete navalis-test-$i
done

make_node router 1
make_node router 2 1

make_node nat 3 1
make_node nat 4 3
make_node nat 5 3

make_node host 6 4
make_node host 7 4
make_node host 8 5

make_node nat 9 2
make_node host 10 9

ip netns exec navalis-test-1 ip route add default via 192.168.2.2

ip netns exec navalis-test-1 sysctl -w net.ipv6.conf.all.forwarding=1
ip netns exec navalis-test-2 sysctl -w net.ipv6.conf.all.forwarding=1

